package com.jhd.fuzhou.view.special;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CertificateUtil;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.SignActivity;
import com.jhd.fuzhou.vo.AskingRecord;
import com.jhd.fuzhou.vo.CheckValue;
import com.jhd.fuzhou.vo.GlobalDictionaryVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.Upload;

import net.zigin.commons.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;
import static com.jhd.fuzhou.view.login.MainActivity.qaList;

public class SpecialAskingRecordActivity extends BaseActivity {

    @BindView(R.id.btn_made_document)
    Button btn_made_document;
    @BindView(R.id.rel_startTime)
    RelativeLayout rel_startTime;
    @BindView(R.id.rel_EndTime) RelativeLayout rel_EndTime;
    @BindView(R.id.tv_startTime)
    TextView tv_startTime;
    @BindView(R.id.tv_endTime)TextView tv_endTime;
    @BindView(R.id.et_person_questioned)
    EditText et_person_questioned;//被询问人，是询问机构
    @BindView(R.id.rb_status_1)RadioButton rb_status_1;//性别男
    @BindView(R.id.rb_status_2)RadioButton rb_status_2;//性别女
    @BindView(R.id.radioGroup)RadioGroup radioGroup;
    @BindView(R.id.et_age)EditText et_age;//年龄
    @BindView(R.id.et_address)EditText et_address;//住址
    @BindView(R.id.et_certificate_no)EditText et_certificate_no;//证件号码
    @BindView(R.id.et_inquiry_address)EditText et_inquiry_address;//询问地址
    @BindView(R.id.rel_certificate_type)RelativeLayout rel_certificate_type;//证件类型
    @BindView(R.id.rel_inquiry_authority)RelativeLayout rel_inquiry_authority;//询问机关,暂不需要
    @BindView(R.id.rel_inquiry_content)RelativeLayout rel_inquiry_content;//询问内容，点击跳转添加页面
    @BindView(R.id.tv_certificate_type)TextView tv_certificate_type;//证件类型
    @BindView(R.id.tv_inquiry_authority)TextView tv_inquiry_authority;//询问机关
    private Context context= this;
    private CheckValue checkValue;
    private List<GlobalDictionaryVo> globalDictionaryVoList;
    private AlertDialog _alertDialog=null;
    @BindView(R.id.iv_party_sign)
    ImageView iv_party_sign;//当事人签名
    @BindView(R.id.iv_Supervisor1_sign)ImageView iv_Supervisor1_sign;//监督员1签名
    @BindView(R.id.iv_Supervisor2_sign)ImageView iv_Supervisor2_sign;//监督员2签名
    @BindView(R.id.tv_certificate_name1)TextView tv_certificate_name1;//监督员1签名
    @BindView(R.id.tv_certificate_name2)TextView tv_certificate_name2;//监督员2签名
    @BindView(R.id.tv_asking_record)TextView tv_asking_record;//询问问题的状态
    private String fileUrl;
    public AskingRecord askingRecord;
    private Bitmap bitmap0;
    private Upload upload1,upload2,upload3;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_asking_record);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        askingRecord= supervisionInspectionVo.getAskingRecord();
        if(askingRecord==null){
            askingRecord=new AskingRecord();
        }
        if(askingRecord.getQaList()!=null){
            qaList=askingRecord.getQaList();
        }else{
            qaList=new ArrayList<>();
        }
        if(qaList.size()!=0){
            tv_asking_record.setText("已询问");
            tv_asking_record.setTextColor(getResources().getColor(R.color.search));
        }else{
            tv_asking_record.setText("未询问");
            tv_asking_record.setTextColor(getResources().getColor(R.color.black));
        }
        fileUrl=getIntent().getExtras().getString("fileUrl");
        bitmap0=((BitmapDrawable)iv_party_sign.getDrawable()).getBitmap();
        getCheckValue();//获取身份证件类型
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
//        takeDocumentNo();
        tv_inquiry_authority.setText(supervisionInspectionVo.getSuperviseSector());
        EditTextView.TextViewChange(tv_inquiry_authority,context);
        tv_certificate_name1.setText("监督员"+ supervisionInspectionVo.getFirstSupervisorName()+"签名");//监督员1名字
        EditTextView.TextViewChange(tv_certificate_name1,context);
        tv_certificate_name2.setText("监督员"+ supervisionInspectionVo.getSecondSupervisorName()+"签名");//监督员2名字
        EditTextView.TextViewChange(tv_certificate_name2,context);
        tv_startTime.setText(StringUtil.isNullOrEmpty(askingRecord.getStartTime())?"请选择":askingRecord.getStartTime());
        EditTextView.TextViewChange(tv_startTime,context);
        tv_endTime.setText(StringUtil.isNullOrEmpty(askingRecord.getEndTime())?"请选择":askingRecord.getEndTime());
        EditTextView.TextViewChange(tv_endTime,context);
        et_person_questioned.setText(StringUtil.isNullOrEmpty(askingRecord.getPerson())? supervisionInspectionVo.getContactPerson():askingRecord.getPerson());
        et_address.setText(StringUtil.isNullOrEmpty(askingRecord.getAddress())? supervisionInspectionVo.getInspectionLocation():askingRecord.getAddress());
        tv_certificate_type.setText(StringUtil.isNullOrEmpty(askingRecord.getCertificateType())?"居民身份证":askingRecord.getCertificateType());
        EditTextView.TextViewChange(tv_certificate_type,context);
        et_certificate_no.setText(StringUtil.isNullOrEmpty(askingRecord.getCertificateNo())?"":askingRecord.getCertificateNo());
        CertificateUtil.check(et_certificate_no,rb_status_1,rb_status_2,et_age,context);
        et_inquiry_address.setText(StringUtil.isNullOrEmpty(askingRecord.getAskingAddress())? supervisionInspectionVo.getInspectionLocation():askingRecord.getAskingAddress());
        upload1=supervisionInspectionVo.getUpload1();upload2=supervisionInspectionVo.getUpload2();upload3=supervisionInspectionVo.getUpload3();
        if(upload1!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/1.png");
            iv_party_sign.setImageBitmap(bitmap);
        }
        if(upload2!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/2.png");
            iv_Supervisor1_sign.setImageBitmap(bitmap);
        }
        if(upload3!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/3.png");
            iv_Supervisor2_sign.setImageBitmap(bitmap);
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(qaList.size()!=0){
            tv_asking_record.setText("已询问");
            tv_asking_record.setTextColor(getResources().getColor(R.color.black));
        }else{
            tv_asking_record.setText("未询问");
            tv_asking_record.setTextColor(getResources().getColor(R.color.search));
        }
    }

    @OnClick({R.id.btn_made_document,R.id.rel_startTime,R.id.rel_EndTime,R.id.rel_certificate_type,R.id.rel_inquiry_authority,
            R.id.rel_inquiry_content,R.id.iv_party_sign,R.id.iv_Supervisor1_sign,R.id.iv_Supervisor2_sign,
            R.id.et_person_questioned,R.id.et_certificate_no,R.id.et_inquiry_address,R.id.et_address})
    public void onClick(View view){
        Intent intent  = new Intent(context, SignActivity.class);
        switch (view.getId()){
            case R.id.et_person_questioned:
                TextDialog.showDialog(context,"被询问人",et_person_questioned);
                break;
            case R.id.et_certificate_no:
                if(tv_certificate_type.getText().toString().equals("请选择")){
                    CustomToast.showText(context, "请先选择身份证件类型", 3000, 0, 0).show();
                }else{
                    if(tv_certificate_type.getText().toString().equals("居民身份证")){
                        TextDialog.showCertificateDialog(context,"身份证号",et_certificate_no,radioGroup,rb_status_1,rb_status_2,et_age);
                    }else{
                        TextDialog.showDialog(context, tv_certificate_type.getText().toString(), et_certificate_no);
                    }
                }
                break;
            case R.id.et_inquiry_address:
                TextDialog.showDialog(context,"询问地址",et_inquiry_address);
                break;
            case R.id.et_address:
                TextDialog.showDialog(context,"住址",et_address);
                break;

            case R.id.btn_made_document:
                if(tv_startTime.getText().toString().equals("请选择")){
                    CustomToast.showText(context,"请选择询问开始时间!",3000,0,0).show();
                    break;
                }
                if(tv_endTime.getText().toString().equals("请选择")){
                    CustomToast.showText(context,"请选择询问结束时间!",3000,0,0).show();
                    break;
                }
                if(et_person_questioned.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入被询问人姓名!",3000,0,0).show();
                    break;
                }
                if(!rb_status_1.isChecked()&&!rb_status_2.isChecked()){
                    CustomToast.showText(context,"请选择性别!",3000,0,0).show();
                    break;
                }
                if(et_age.getText().toString().equals("")){
                    CustomToast.showText(context,"年龄未带出,请输入正确的18位身份证号码!",3000,0,0).show();
                    break;
                }
                if(et_address.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入被询问人住址!",3000,0,0).show();
                    break;
                }
                if(tv_certificate_type.getText().toString().equals("请选择")){
                    CustomToast.showText(context,"请输入被询问人证件类型!",3000,0,0).show();
                    break;
                }
                if(et_certificate_no.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入被询问人证件号码!",3000,0,0).show();
                    break;
                }
                if(et_inquiry_address.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入询问地点!",3000,0,0).show();
                    break;
                }
                if(qaList.size()==0){
                    CustomToast.showText(context,"您还未询问问题!",3000,0,0).show();
                    break;
                }
                setAskingRecord();
                Bitmap bitmap1=((BitmapDrawable)iv_party_sign.getDrawable()).getBitmap();
                Bitmap bitmap2=((BitmapDrawable)iv_Supervisor1_sign.getDrawable()).getBitmap();
                Bitmap bitmap3=((BitmapDrawable)iv_Supervisor2_sign.getDrawable()).getBitmap();
                if(bitmap1==bitmap0){
                    supervisionInspectionVo.setSign1(false);
                }else{
                    supervisionInspectionVo.setSign1(true);
                }
                if(bitmap2==bitmap0){
                    supervisionInspectionVo.setSign2(false);
                }else{
                    supervisionInspectionVo.setSign2(true);
                }
                if(bitmap3==bitmap0){
                    supervisionInspectionVo.setSign3(false);
                }else{
                    supervisionInspectionVo.setSign3(true);
                }
                Gson gson = new Gson();
                Intent intent1=new Intent(context, SpecialDocumentEnquiryRecordActivity.class);
                intent1.putExtra("fileUrl",fileUrl);
                intent1.putExtra("type","询问笔录");
                intent1.putExtra("askingRecord",gson.toJson(askingRecord));
                startActivity(intent1);
                break;
            case R.id.rel_startTime:
                getTimeDialog(tv_startTime,context);
                break;
            case R.id.rel_EndTime:
                getTimeDialog(tv_endTime,context);
                break;
            case R.id.rel_certificate_type:
                if(checkValue==null){
                    getCheckValue();
                }else{
                    globalDictionaryVoList = checkValue.getGlobalDictionaryVoMap();
                    dialogShow("身份证件类型",tv_certificate_type,globalDictionaryVoList);
                }
                break;
            case R.id.rel_inquiry_authority://询问机关

                break;
            case R.id.rel_inquiry_content:
                startActivity(new Intent(context, SpecialAskingListActivity.class));
                break;
            case R.id.iv_party_sign:
                intent.putExtra("position","1");
                startActivityForResult(intent,1);
                break;
            case R.id.iv_Supervisor1_sign:
                intent.putExtra("position","2");
                startActivityForResult(intent,1);
                break;
            case R.id.iv_Supervisor2_sign:
                intent.putExtra("position","3");
                startActivityForResult(intent,1);
                break;
        }
    }
    public void dialogShow(String title,TextView textView, List<GlobalDictionaryVo> globalDictionaryVoList) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_choose, null);
        final androidx.appcompat.app.AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        RecyclerView rv_choose = (RecyclerView) view.findViewById(R.id.rv_choose);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_choose.setLayoutManager(layoutManage);
        tv_title.setText(title);//标题要改一下
        CheckAdapter recyclerAdapter=new CheckAdapter(textView,_alertDialog,globalDictionaryVoList);
        rv_choose.setAdapter(recyclerAdapter);
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }
    public class CheckAdapter extends RecyclerView.Adapter<CheckAdapter.ViewHolder> {
        private List<GlobalDictionaryVo> globalDictionaryVoList;
        private TextView textView;
        private AlertDialog _alertDialog;
        private int checkPosition=-1;

        public CheckAdapter(TextView textView, AlertDialog _alertDialog, List<GlobalDictionaryVo> globalDictionaryVoList) {
            this.globalDictionaryVoList = globalDictionaryVoList;
            this._alertDialog = _alertDialog;
            this.textView = textView;
        }

        @NonNull
        @Override
        public CheckAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            CheckAdapter.ViewHolder viewHolder = new CheckAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull CheckAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(globalDictionaryVoList.get(position).getKey());
            if(globalDictionaryVoList.get(position).getKey().equals(textView.getText().toString())){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                holder.image.setVisibility(View.GONE);
            }

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textView.setText(globalDictionaryVoList.get(position).getValue());
                    holder.image.setVisibility(View.VISIBLE);
                    _alertDialog.dismiss();
                    checkPosition=position;
                    notifyDataSetChanged();
                }
            });

            if(position==checkPosition){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                if(checkPosition!=-1){
                    holder.image.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public int getItemCount() {
            return globalDictionaryVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }
    private void getCheckValue(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application, "http://192.168.1.69:9004/");//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        JSONArray jsonArray=new JSONArray();
        jsonArray.add("身份证件类型(国)");
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("nameList",jsonArray);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getValueList(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            checkValue= JSON.parseArray(jsonForResult.getData().toString(), CheckValue.class).get(0);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取身份证件类型失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            byte[] bis = data.getByteArrayExtra("signBitmap");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            File files=new File(getExternalFilesDir(null).getPath()+"/Download/");
            if(!files.exists())files.mkdirs();
            if(data.getStringExtra("position").equals("1")){
                iv_party_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/1.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload1(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/1.png");
            }else if(data.getStringExtra("position").equals("2")){
                iv_Supervisor1_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/2.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload2(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/2.png");
            }else if(data.getStringExtra("position").equals("3")){
                iv_Supervisor2_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/3.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload3(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/3.png");
            }
        }
    }
    public void setAskingRecord(){
        askingRecord.setStartTime(tv_startTime.getText().toString());
        askingRecord.setEndTime(tv_endTime.getText().toString());
        askingRecord.setPerson(et_person_questioned.getText().toString());
        if(rb_status_1.isChecked()){
            askingRecord.setGender("男");
        }else{
            askingRecord.setGender("女");
        }
        askingRecord.setAge(et_age.getText().toString());
        askingRecord.setAddress(et_address.getText().toString());
        askingRecord.setCertificateType(tv_certificate_type.getText().toString());
        askingRecord.setCertificateNo(et_certificate_no.getText().toString());
        askingRecord.setQaList(qaList);
        askingRecord.setAskingAddress(et_inquiry_address.getText().toString());
        askingRecord.setAskingUnit(tv_inquiry_authority.getText().toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setAskingRecord();
        supervisionInspectionVo.setAskingRecord(askingRecord);
        qaList.clear();
    }
}